#include "../include/MmapFinder.h"

#include <map>
#include <vector>
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <sys/mman.h>


void MmapFinder::setFiles(std::vector<std::string> _files) {
    m_files = _files;
}

void MmapFinder::setParameters(std::map<const char*, bool> _params) {
    m_parameters = _params;
}

void MmapFinder::setPattern(std::string _pattern) {
    m_pattern = _pattern;
}

void MmapFinder::find() {
    unsigned        filesCounter = 0;
    int             length;
    FILE*           fd;
    char*           map;
    unsigned        linesCounter = 1;
    size_t          found;
    std::string     line;
    while (filesCounter < m_files.size()) {
        std::cout << "\r\n" << m_files[filesCounter].c_str() << std::endl;
        fd = fopen(m_files[filesCounter].c_str(), "r");
        fseek(fd,0,SEEK_END);
        length = ftell(fd);
        rewind(fd);
        map = (char*)(mmap(0,length, PROT_READ, MAP_SHARED, fileno(fd), 0));

        for (size_t i = 0; i < strlen(map); ++i) {
            if (map[i] != '\n') {
                line += map[i];
                continue;
            }
            found = line.find(this->m_pattern);
            if (found != std::string::npos)
                std::cout << linesCounter << ". " << line << std::endl << std::endl;
            ++linesCounter;
            line.clear();
        }
        fclose(fd);
        ++filesCounter;
        linesCounter = 0;
    }
}
